package com.wy.system.utils;

import com.wy.model.entity.Permission;

import java.util.ArrayList;
import java.util.List;

public class PermissionHelper {
  //构建树形结构
  public static List<Permission> buildTree(List<Permission> permissionList){
    //创建集合封装最终的数据
    List<Permission> trees = new ArrayList<>();
    //遍历所有菜单集合
    for (Permission permission: permissionList) {
      //找到递归的入口,parentid=0
      if (permission.getParentId().longValue() == 0){
        trees.add(findChildren(permission,permissionList));
      }
    }
    return trees;
  }

  //从根节点进行递归查询，查询子节点
  //判断id == parentid?，如果相同是子节点，进行数据封装
  private static Permission findChildren(Permission permission, List<Permission> permissionList) {
    //数据初始化
    permission.setChildren(new ArrayList<Permission>());
    //递归遍历查找
    for (Permission it : permissionList) {
      //获取当前菜单id
      Integer cid = permission.getId();
      //获取所有菜单parentid
      Integer parentId = it.getParentId();
      //比对
      if (cid == parentId){
        if (permission.getChildren() == null){
          permission.setChildren(new ArrayList<>());
        }
        permission.getChildren().add(findChildren(it,permissionList));
      }
    }
    return permission;
  }
}
